define(['app', 'ace-language-tools'], function(app) {
    app.controller('diffFile', function($http, $uibModalInstance, _context) {
        var self = this;

        var diffViewer = null;

        self.init = function() {
            self.file = _context.file;

            diffViewer = ace.edit('diff-viewer', {
                mode: 'ace/mode/diff',
                theme: 'ace/theme/chrome',
                cursorStyle: 'slim',
                fontSize: 14,
                readOnly: true,
                useWorker: false,
                showPrintMargin: false,
                showFoldWidgets: false,
                displayIndentGuides: false,
                highlightGutterLine: false,
                highlightActiveLine: false,
                autoScrollEditorIntoView: true
            });

            $http.post('/note/git/diff', {
                file: _context.path,
                sha: _context.sha,
                shb: _context.shb
            }).then(function(response) {
                if (response.status == 200) {
                    var diffLines = response.data;
                    if (!_.isEmpty(diffLines)) {
                        var editorSession = diffViewer.getSession();
                        // line number
                        editorSession.gutterRenderer = {
                            getDiffText: function(session, row) {
                                var line = diffLines[row];
                                if (line) {
                                    return [line.oldLineno, line.newLineno];
                                }
                                return [row, row];
                            },
                            getWidth: function(session, lastLineNumber, config) {
                                return Math.ceil(lastLineNumber.toString().length * config.characterWidth + 10) * 2;
                            }
                        };
                        // highlight
                        _.forEach(diffLines, function(line, row) {
                            var className = (line.origin == '+' ? 'git-diff-add' :
                                    (line.origin == '-' ? 'git-diff-remove' : 'git-diff-line'));
                            editorSession.addGutterDecoration(row, className);
                            editorSession.highlightLines(row, row, className, false);
                        });
                        // set value
                        diffViewer.setValue(_.map(diffLines, function(line) {
                            return (line.origin == '@' ? '' : line.origin) + line.content;
                        }).join('\n'), -1);
                        diffViewer.resize();
                    }
                }
            });
        }

        self.resize = function() {
            diffViewer.resize();
        }

        self.close = function() {
            $uibModalInstance.close();
        }
    });
});
